package com.ferusdev.smsbackup;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

	private Button exportButton, importButton;
	private int countCursor = 0, csvHeadLine = 1;
	private List<String> smsBuffer = new ArrayList<String>();
	private Toast toast;
	private Uri mSmsinboxQueryUri = Uri.parse("content://sms/");

	private List<String> list;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		exportButton = (Button) findViewById(R.id.exportButton);
		importButton = (Button) findViewById(R.id.importButton);
		exportButton.setOnClickListener(this);
		importButton.setOnClickListener(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.exportButton:
			Log.d("pulsante export","export");
			exportButton.setEnabled(false);
			importButton.setEnabled(false);
			if(checkExternalStorage()){
				toast = Toast.makeText(this, "Inizio Esportazione...", Toast.LENGTH_SHORT);
				toast.show();
				exportSMS();
				toast = Toast.makeText(this, "Fine Esportazione...", Toast.LENGTH_SHORT);
				toast.show();
			}else{
				Log.w("External Storage", "External Storage Check Fail");
				toast = Toast.makeText(this, "Attenzione!!! \nSD-Card non presente! \nOperazione non effettuata.", Toast.LENGTH_SHORT);
				toast.show();
			}			
			exportButton.setEnabled(true);
			importButton.setEnabled(true);
			break;
		case R.id.importButton:
			Log.d("pulsante import","import");
			exportButton.setEnabled(false);
			importButton.setEnabled(false);
			if(checkExternalStorage()){
				toast = Toast.makeText(this, "Inizio Importazione...", Toast.LENGTH_SHORT);
				toast.show();
				importSMS();
				toast = Toast.makeText(this, "Fine Importazione...", Toast.LENGTH_SHORT);
				toast.show();
			}else{
				Log.w("External Storage", "External Storage Check Fail");
				toast = Toast.makeText(this, "Attenzione!!! \nSD-Card non presente! \nOperazione non effettuata.", Toast.LENGTH_SHORT);
				toast.show();
			}
			exportButton.setEnabled(true);
			importButton.setEnabled(true);
			break;
		}
	}

	private void  exportSMS(){
		smsBuffer.clear();
		Cursor cursor1 = getContentResolver().query(
				mSmsinboxQueryUri, 
				new String[] { "_id", "thread_id", "address", "person", "date", "body", "type" }, null, null, null);
		String[] columns = new String[] { "_id", "thread_id", "address", "person", "date", "body", "type" };
		if (cursor1 != null && cursor1.getCount() > 0) {
			countCursor = cursor1.getCount();
			String countCursorStr = Integer.toString(countCursor);
			Log.d("Count",countCursorStr);
			while (cursor1.moveToNext()) {
				String messageId = cursor1.getString(cursor1.getColumnIndex(columns[0]));
				String threadId = cursor1.getString(cursor1.getColumnIndex(columns[1]));
				String address = cursor1.getString(cursor1.getColumnIndex(columns[2]));
				String name = cursor1.getString(cursor1.getColumnIndex(columns[3]));
				String date = cursor1.getString(cursor1.getColumnIndex(columns[4]));
				String msg = cursor1.getString(cursor1.getColumnIndex(columns[5]));
				String type = cursor1.getString(cursor1.getColumnIndex(columns[6]));

				smsBuffer.add(messageId + ";"+ threadId+ ";"+ address + ";" + name + ";" + date + ";" + msg + ";" + type);
			}           
			generateCSV(smsBuffer);
		}else{
			//
		}
	}
	
	private void importSMS(){
		List<String[]> smsList = new LinkedList<String[]>();
		smsList = getCSV();
		if(smsList != null && smsList.size() > 0){
			for(String[] data : smsList){
				ContentValues values = new ContentValues();
				values.put("address", data[2]);
				values.put("person", data[3]);
				values.put("date", data[4]);
				values.put("body", data[5]);
				values.put("type", data[6]);
				getContentResolver().insert(mSmsinboxQueryUri, values);
				values.clear();
			}	        
		}else{
			//sms not found
		}
		
	}

	private void generateCSV(List<String> smsBuffer2){
		try{
			/*Date date= new java.util.Date();
			String timestamp = new Timestamp(date.getTime()).toString();
			String smsFile = "SmsBackup-"+ timestamp + ".csv";*/
			
			//TODO Implementare file manager!!!
			String smsFile = "SmsBackup.csv";
			
			String pathStorage = Environment.getExternalStorageDirectory().toString();
			String storage_path = pathStorage + File.separator + smsFile;
			FileWriter write = new FileWriter(storage_path);
			write.append("messageId; threadId; Address; Name; Date; msg; type");
			write.append('\n');

			for (String s : smsBuffer2){
				write.append(s);
				write.append('\n');
			}
			write.flush();
			write.close();

		}

		catch (NullPointerException e){
			Log.e("NullPointerException",e.getMessage());
			e.printStackTrace();
		}
		catch (IOException e){
			Log.e("IOException",e.getMessage());
			e.printStackTrace();
		}
		catch (Exception e){
			Log.e("Exception",e.getMessage());
			e.printStackTrace();
		}

	}
	
	private List<String[]> getCSV(){
		List<String[]> smsLL = new LinkedList<String[]>();
		String smsFile = "SmsBackup.csv";
		String pathStorage = Environment.getExternalStorageDirectory().toString();
		String storage_path = pathStorage + File.separator + smsFile;
		BufferedReader br = null;
		String line = "";
		String cvsSplitBy = ";";
		try {
			br = new BufferedReader(new FileReader(storage_path));
			int countLine = 0;
			while ((line = br.readLine()) != null) {
				countLine++;
				if(csvHeadLine != countLine){
					String[] smsLine = line.split(cvsSplitBy);
					smsLL.add(smsLine);
				}
			}
		} catch (FileNotFoundException e) {
			Log.e("FileNotFoundException",e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			Log.e("IOException",e.getMessage());
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					Log.e("IOException",e.getMessage());
					e.printStackTrace();
				}
			}
		}			
		return smsLL;		
	}

	private boolean checkExternalStorage(){
		boolean check = false, mExternalStorageAvailable = false, mExternalStorageWriteable = false;
		//String state = Environment.getExternalStorageState();
		String state = Environment.getExternalStorageState();
		Log.d("Storage State", state);
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			// We can read and write the media
			mExternalStorageAvailable = mExternalStorageWriteable = true;
		} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
			// We can only read the media
			mExternalStorageAvailable = true;
			mExternalStorageWriteable = false;
		} else {
			// Something else is wrong. It may be one of many other states, but all we need
			//  to know is we can neither read nor write
			mExternalStorageAvailable = mExternalStorageWriteable = false;
		}

		if(mExternalStorageAvailable && mExternalStorageWriteable){
			check = true;
		}else if(!mExternalStorageAvailable){
			Log.w("External Storage", "SDCard is not Available!");
		}else if(!mExternalStorageWriteable){
			Log.w("External Storage", "SDCard is not Writable!");
		}else{
			Log.e("External Storage", "Error Access SDCard");
		}
		return check;
		
	}
	private void chooseFile(){
//		File file = new File(Environment.getExternalStorageDirectory().toString());
//		if (!file.exists()) {
//			file.mkdirs();
//		}
		ListView lv = (ListView) findViewById(R.id.List);
		list = getSD();
//		lv.setAdapter((ListAdapter) new ArrayAdapter<String>(MainActivity.this, R.layout.explorer, list));
		lv.setAdapter((ListAdapter) new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list));
		Log.d("LOG", "FIRE !!!! " ); 
		
		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// When clicked, show a toast with the TextView text
				Toast.makeText(MainActivity.this,"Clicked an item", Toast.LENGTH_LONG).show();
				Intent intent = new Intent(MainActivity.this, MainActivity.class);
				startActivity(intent);
			}
		});
	}
	private List<String> getSD() {
        List<String> item = new ArrayList<String>();
        File f = new File(Environment.getExternalStorageDirectory().toString());
        File[] files = f.listFiles();

        for(int i = 0; i < files.length; i++) {
            File file = files[i];
            //take the file name only
            long size = file.length()/1024;

            String myfile = file.getPath().substring(file.getPath().lastIndexOf("/")+1,file.getPath().length()).toLowerCase(); 
            //item.add(myfile);
            item.add(myfile+"             "+"Size:"+size+" KB");

            // Log.d("LOG", "fs "+file.length());
            //item.add(file.length());
        }
        return item;
    }
}
